package com.wxj.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader;
import com.wxj.edu.client.VodClient;
import com.wxj.edu.entity.Video;
import com.wxj.edu.mapper.VideoMapper;
import com.wxj.edu.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author wxj
 * @since 2021-03-10
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    /**
     * 1 根据课程id删除小节
     * TODO 删除小节，删除对应视频
     *
     * @param courseId
     */
    @Override
    public void removeVideoByCourseId(String courseId) {
        //根据课程id查询课程所有的视频id
        QueryWrapper<Video> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id", courseId);
        wrapperVideo.select("video_source_id");
        List<Video> videoList = baseMapper.selectList(wrapperVideo);

        //List<Video>变成List<String>
        List<String> videoIds = new ArrayList<>();
        for (Video eduVideo : videoList) {
            String videoSourceId = eduVideo.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) {
                videoIds.add(videoSourceId);
            }
        }
        if (videoIds.size() > 0) {
            vodClient.deleteBatch(videoIds);
        }
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        baseMapper.delete(wrapper);

    }

    /**
     * 2 根据章节id删除小节
     * TODO 删除小节，删除对应视频
     *
     * @param chapterId
     */
    @Override
    public void removeVideoByChapterId(String chapterId) {
        //根据课程id查询课程所有的视频id
        QueryWrapper<Video> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("chapter_id", chapterId);
        wrapperVideo.select("video_source_id");
        List<Video> videoList = baseMapper.selectList(wrapperVideo);


        //List<Video>变成List<String>
        List<String> videoIds = new ArrayList<>();

        for (int i = 0; i < videoList.size(); i++) {
            if (videoList.get(i) != null) {
                Video eduVideo = videoList.get(i);
                String videoSourceId = eduVideo.getVideoSourceId();
                if (!StringUtils.isEmpty(videoSourceId)) {
                    videoIds.add(videoSourceId);
                }
            }
        }

        if (videoIds.size() > 0) {
            vodClient.deleteBatch(videoIds);
        }

        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", chapterId);
        baseMapper.delete(wrapper);
    }


}
